import axios, { type InternalAxiosRequestConfig, type AxiosResponse } from 'axios'
import { showToast, showLoadingToast, closeToast } from 'vant'

// API基础配置
const API_BASE_URL = '/api'

// 创建axios实例
const request = axios.create({
  baseURL: API_BASE_URL,
  timeout: 30000,
  headers: {
    'Content-Type': 'application/json'
  }
})

// 请求拦截器
request.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    // 添加loading状态
    if (config.headers && !config.headers['no-loading']) {
      showLoadingToast({
        message: '加载中...',
        forbidClick: true,
        duration: 0
      })
    }

    // 添加token
    const token = localStorage.getItem('token')
    if (token && config.headers) {
      config.headers.Authorization = `Bearer ${token}`
    }

    return config
  },
  (error) => {
    closeToast()
    return Promise.reject(error)
  }
)

// 响应拦截器
request.interceptors.response.use(
  (response: AxiosResponse) => {
    closeToast()

    const { code, message, data } = response.data

    if (code === 200) {
      return data
    } else {
      showToast({
        type: 'fail',
        message: message || '请求失败'
      })
      return Promise.reject(new Error(message || '请求失败'))
    }
  },
  (error) => {
    closeToast()

    if (error.response) {
      const { status, data } = error.response

      if (status === 401) {
        // token过期，清除本地存储并跳转登录
        localStorage.removeItem('token')
        localStorage.removeItem('userInfo')
        window.location.href = '/login'
        return Promise.reject(error)
      }

      const message = data?.message || `请求失败 (${status})`
      showToast({
        type: 'fail',
        message
      })
    } else if (error.request) {
      showToast({
        type: 'fail',
        message: '网络请求失败，请检查网络连接'
      })
    } else {
      showToast({
        type: 'fail',
        message: error.message || '请求失败'
      })
    }

    return Promise.reject(error)
  }
)

export default request